package com.lixl.concurrent.thread;

public class Car extends Thread {
	
	private long clock=0;
	
	private int meterClock = 0;
	
	public String driver;
	
	public Car(String carNum, String driver) {
		this.setName(carNum);
		this.driver = driver;
	}
	
	@Override
	public void run() {
		System.out.println(this.getName()+"\t"+driver+" is running");
		this.clock = System.currentTimeMillis();
		while(true){
			meterClock++;
			if(meterClock==100){
				try {
					System.out.println(this.getName()+"\t"+driver+" 休息2s");
					sleep(1000*2);
					System.out.println(this.getName()+"\t"+driver+" 休息完了");
				} catch (InterruptedException e) {
					e.printStackTrace();
				}
			}
			
			//张三跑到10000时停下来接个3s的电话
			if(meterClock==10000 && this.getName().equals("1001")){
				synchronized (this) {
					System.out.println(this.getName()+"\t"+driver+" wait 3s");
					try {
						this.wait(3000);
					} catch (InterruptedException e) {
						e.printStackTrace();
					}
					System.out.println(this.getName()+"\t"+driver+" wait 3s结束");
				}
			}
			
			//开车超过5000的，强制去等待
			if((getRunTime()>=6000 && getRunTime()<=7000)&& this.getName().equals("1001") && !"WAITING".equals(this.getState().name())){
				Police.syncWait(this, Police.getLock());
			}
			if(meterClock>=Integer.MAX_VALUE/2){
				break;
			}
		}
	}
	
	public int getMeterClock(){
		return meterClock;
	}
	
	public long getRunTime(){
		if(clock==0){
			return 0;
		}
		long l = System.currentTimeMillis()-clock;
		if(l<0||l>Long.MAX_VALUE){
			return 0;
		}
		return l;
	}
	

}
